在Day-2,我嘗試直接把整數跟字串用 + 串接:
score = 90
print("成績是:" + score)
結果出現錯誤訊息:
TypeError: can only concatenate str (not "int") to str
這讓我發現 Python 不會自動幫整數轉成字串,必須用 str() 轉換,或使用逗號分隔法:
print("成績是:" + str(score)) # 手動轉型
print("成績是:", score) # 逗號分隔,自動轉換
(1)+ 號串接
name = "Chloe"
print("Hello" + name + "!")
缺點:需要頻繁轉型,容易忘記加 str()。
(2)逗號分隔
print("Hello", name, "!")
適合快速輸出,但格式控制較少。
(3)f-string
print(f"Hello,{name}!")
可直接將變數嵌入字串中
name = input("Enter your name:")
score = float(input("Enter your score:"))
print(f"{name} 's score is {score:.1f}")
:.1f 控制小數點顯示一位
今天學了程式的格式化輸出,算是一次的複習!因為在 Day-2 我本來嘗試將整數變數接到字串後面時,顯示錯誤訊息:
TypeError: can only concatenate str (not "int") to str
為了解決這個問題,就提前學會了str() 轉型、逗號分隔變數,以及 f-string 的語法!
而今天正式系統性地學到「數值與字串的處理方式」、「print 的格式化輸出」,就像是把之前遇到的實戰經驗重新整理一遍,讓我對字串與變數之間的結合方式更有架構、更有自信!
明天我會學習條件判斷與 if、elif、else 陳述式,讓程式根據不同情況產生不同回應,開始進入有邏輯的判斷流程,也讓互動變得更智慧、更多變!